package main

import (
	"fmt"
	"strings"
	"time"

	// alias别名
	ginzap "github.com/gin-contrib/zap"
	"github.com/gin-gonic/gin"
	_ "github.com/go-sql-driver/mysql"
	"github.com/google/logger"
	"github.com/topaz-h/gin-web/controller"
	"github.com/topaz-h/gin-web/tools"
	"go.uber.org/zap"
)

// var (
// 	g errgroup.Group
// )

func main() {
	// 解析配置文件json
	config, err := tools.ParseConfig("./config/app.json")
	if err != nil {
		logger.Error(err.Error())
	}

	// 数据库连接，创建xorm引擎
	_, err = tools.CreateOrmEngine(config)
	if err != nil {
		logger.Error(err.Error())
		return
	}

	// 初始化redis
	// tools.InitRediStore()

	// [Gin + Zap](https://blog.csdn.net/Kingtu_linux/article/details/105960756)
	tools.SetLogs(zap.DebugLevel, tools.LOGFORMAT_CONSOLE, "./tmp/gin-zap.log")

	if err := tools.InitTrans("zh"); err != nil {
		fmt.Printf("init trans failed, err:%v\n", err)
		return
	}

	// app := gin.Default()// 使用gin默认的中间件
	app := gin.New() // 使用第三方中间件
	// 使用zap日志库
	app.Use(ginzap.Ginzap(zap.L(), time.RFC3339, true))
	app.Use(ginzap.RecoveryWithZap(zap.L(), true))
	// 使用全局中间件
	app.Use(Cors())

	// 设置静态资源目录
	app.Static("/static", "./static")

	// 调用注册路由函数
	registerRouter(app)

	if err := app.Run(config.AppHost + ":" + config.AppPort); err != nil {
		zap.L().Fatal("HTTP Server启动失败", zap.Error(err))
	}
}

// 注册路由
func registerRouter(router *gin.Engine) {
	new(controller.IndexController).Router(router)
	new(controller.AuthController).Router(router)
	// new(controller.UploadController).Router(router)
}

// Cors cross-origin-resource-share 后端全局跨域访问请求中间件
// 其中的Access-Control-Allow-Origin的设置，表示允许进行跨域访问，*表示可以访问所有域。同时，通过Header方法进行了其他的设置。
func Cors() gin.HandlerFunc {
	return func(c *gin.Context) {
		method := c.Request.Method
		origin := c.Request.Header.Get("Origin")
		var headerKeys []string
		for key := range c.Request.Header {
			headerKeys = append(headerKeys, key)
		}
		headerStr := strings.Join(headerKeys, ",")
		if headerStr != "" {
			headerStr = fmt.Sprintf("access-control-allow-origin, access-control-allow-headers, %s", headerStr)
		} else {
			headerStr = "access-control-allow-origin, access-control-allow-headers"
		}
		if origin != "" {
			c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
			c.Header("Access-Control-Allow-Origin", "*") // 设置允许访问所有域
			c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE")
			c.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Token,session,X_Requested_With,Accept, Origin, Host, Connection, Accept-Encoding, Accept-Language,DNT, X-CustomHeader, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Pragma")
			c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers,Cache-Control,Content-Language,Content-Type,Expires,Last-Modified,Pragma,FooBar")
			c.Header("Access-Control-Max-Age", "172800")
			c.Header("Access-Control-Allow-Credentials", "false")
			c.Set("content-type", "application/json") // 设置返回格式是json
		}

		if method == "OPTIONS" { // 嗅探
			tools.Success(c, "Options Request！允许嗅探")
		}
		// 继续处理请求
		c.Next()
	}
}
